package org.bzjj.tool;

import java.io.ByteArrayInputStream;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.digester.Digester;

public class TmriXmlUtil {
	public static Object parseUTF8XML2Bean(String xmlDoc, String _className,
			String preFix) throws Exception {
		Object _obj = parseXML2Bean(xmlDoc, _className, preFix);
		_obj = decodeObject(_obj);
		return _obj;
	}

	public static Object parseXML2Bean(String xmlDoc, String _className,
			String preFix) throws Exception {
		try {
			Object m_Object = Class.forName(_className).newInstance();
			Map p = BeanUtils.describe(m_Object);
			Set s = p.keySet();
			Iterator i = s.iterator();

			Digester digester = new Digester();
			digester.setValidating(false);
			digester.addObjectCreate("root", m_Object.getClass());
			while (i.hasNext()) {
				Object key = i.next();
				if (!key.equals("class")) {
					digester.addBeanPropertySetter(
							"root/" + preFix + "/" + key.toString(),
							key.toString());
				}
			}
			byte[] src = xmlDoc.getBytes();
			ByteArrayInputStream stream = new ByteArrayInputStream(src);
			return digester.parse(stream);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new Exception("XML文档格式不正确：" + ex.getMessage());
		}
	}
	
	  private static Object decodeObject(Object _obj)
			    throws Exception
			  {
			    Map p = BeanUtils.describe(_obj);
			    Set s = p.keySet();
			    Iterator k = s.iterator();
			    while (k.hasNext())
			    {
			      Object key = k.next();
			      if (!key.equals("class"))
			      {
			        Object value = p.get(key);
			        String m_curValue = (String)value;
			        if (m_curValue == null) {
			          m_curValue = null;
			        } else if ((m_curValue.equals("")) || (m_curValue.toLowerCase().equals("null"))) {
			          m_curValue = "";
			        } else {
			          m_curValue = TmriWrapHelper.decodeUTF8(m_curValue);
			        }
			        p.put(key, m_curValue);
			      }
			    }
			    BeanUtils.populate(_obj, p);
			    return _obj;
			  }
}
